var express = require('express');
var router = express.Router();
const urlLib = require('url');

//挂中间键

// 访问限制中间键
router.use(require('../middlewares/allowCors'))

//token验证
router.use(require('../middlewares/checkToken'))

//c和A
// router.use(require('../middlewares/checkToken'))
router.use(function (req, res, next) {
    
    let urlArr = req.url.toLowerCase().split('/');

    let controller = urlArr[1] ? urlArr[1] : 'index';
    let action = urlArr[2] ? urlArr[2] : 'index';

    req.controller = controller;
    req.action = action;

    let controllerName = '', actionName = '';

    let controllerArr = controller.split('_');

    controllerArr.forEach(c => {
        controllerName += c[0].toUpperCase() + c.substr(1);

    })



    actionName = req.method.toLowerCase() + '_' + urlLib.parse(action).pathname;


    let controllerObj = {}
    try {
        controllerObj = require(`../app/${req.moduleName}/controllers/${controllerName}Controller`)
    } catch (err) {
        throw new Error(`Require Controller ${controllerName} is not exists`)
    }

    if (!controllerObj[actionName]) {
        throw new Error(`Request Method ${controllerName} ${actionName} is not exists`)
    }

    
    controllerObj[actionName](req, res, next)

})


module.exports = router;
